﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using Sunny.UI;

namespace DevelopTool.Forms.TextProcessForms
{
    /// <summary>
    /// 根据模板生成文本
    /// </summary>
    public partial class GenerateTextByTemplateForm : BaseUIPage
    {
        public GenerateTextByTemplateForm()
        {
            InitializeComponent();
        }

        private void TextBatchToTemplateForm_Load(object sender,EventArgs e)
        {

        }

        /// <summary>
        /// 识别参数 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExtractParam_Click(object sender,EventArgs e)
        {
            string templetText = codeEditorTemplate.ContentText;//模板文本

            #region 验证
            if(string.IsNullOrWhiteSpace(templetText) || string.IsNullOrWhiteSpace(templetText.Trim()))
            {
                this.ShowWarningTip("请先填入模板文本");
                codeEditorTemplate.Focus();
                return;
            }
            if(!templetText.Contains("{") || !templetText.Contains("}"))
            {
                this.ShowWarningTip("未识别到参数标识{ }大括号");
                return;
            }

            #endregion

            PnlParam.Controls.Clear();//新增前先删除原有的控件

            var matchList = Regex.Matches(templetText,@"\{[^\}]+\}").OfType<Match>().ToList();//使用正则表达式匹配参数
            matchList.Reverse();

            UIMenuStyle uIMenuStyle = Setting.Theme.ControlThemColor;

            foreach(Match match in matchList)
            {
                //创建参数panl容器控件
                UITitlePanel uITitlePanel = new UITitlePanel
                {
                    AutoSize = true,
                    Dock = DockStyle.Top,
                    Font = codeEditorTemplate.TextEditorControl.Font,
                    Name = "Pnl_" + StringHelper.GetContent(match.Value,"{","}",6),
                    Padding = new Padding(0,20,0,0),
                    Text = "参数：" + match.Value,
                    TitleHeight = 20,
                    Style = UIStyle.Custom,
                    TitleColor = Setting.Theme.BackColor
                };
                uITitlePanel.RectColor = Setting.Theme.BackColor;
                switch(uIMenuStyle)
                {
                    case UIMenuStyle.Black:
                        uITitlePanel.FillColor = ThemHelper.CustomBackColor_Black;
                        uITitlePanel.ForeColor = Color.White;
                        break;
                    case UIMenuStyle.White:
                        uITitlePanel.FillColor = ThemHelper.CustomBackColor_White;
                        uITitlePanel.ForeColor = Color.Black;
                        break;
                }


                //创建参数RichTextBox控件
                UIRichTextBox uIRichTextBox = new UIRichTextBox
                {
                    Dock = DockStyle.Top,
                    TextAlignment = ContentAlignment.TopLeft,
                    Name = "Rtxt_" + StringHelper.GetContent(match.Value,"{","}",6),
                    Font = codeEditorTemplate.TextEditorControl.Font,
                    Style = UIStyle.Custom,
                    TagString = match.Value,
                };
                uIRichTextBox.RectColor = Setting.Theme.BackColor;
                uIRichTextBox.ScrollBarColor = Setting.Theme.BackColor;
                switch(uIMenuStyle)
                {
                    case UIMenuStyle.Black:
                        uIRichTextBox.FillColor = Color.Black;
                        uIRichTextBox.FillColor2 = Color.Black;
                        uIRichTextBox.ForeColor = Color.White;

                        uIRichTextBox.ScrollBarBackColor = Color.FromArgb(66,66,66);
                        break;
                    case UIMenuStyle.White:
                        uIRichTextBox.FillColor = Color.White;
                        uIRichTextBox.FillColor2 = Color.White;
                        uIRichTextBox.ForeColor = Color.Black;

                        uIRichTextBox.ScrollBarBackColor = Color.Gray;
                        break;
                }


                uIRichTextBox.TextChanged += ParamRichTextBox_TextChanged;


                PnlParam.Controls.Add(uITitlePanel);//将panl容器添加到参数栏容器中
                uITitlePanel.Controls.Add(uIRichTextBox);//将文本框控件添加到panl容器中  
            }
        }



        /// <summary>
        /// 生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenerate_Click(object sender,EventArgs e)
        {
            //获得文本控件集合
            List<UIRichTextBox> paramTextBoxList = PnlParam.GetControls<UIRichTextBox>(true);
            if (paramTextBoxList.Count <= 0) {

                this.ShowWarningTip(this.btnExtractParam, "请先识别模板文本");
                return;
            }

            //统计文本框中的值行数
            Dictionary<UIRichTextBox,int> paramCountDic = new Dictionary<UIRichTextBox,int>();
            foreach(UIRichTextBox textBox in paramTextBoxList)
            {
                int count = textBox.Lines.ToList().Count(it => !string.IsNullOrEmpty(it));
                paramCountDic.Add(textBox,count);
            }

            var dicSort = paramCountDic.OrderByDescending(it => it.Value);//以参数条数降序排序

            var mainDic = dicSort.FirstOrDefault();//获取数量最多的参数项

            UIRichTextBox mainParamTextBox = mainDic.Key;
            if(mainParamTextBox == null) return;

            StringBuilder sb = new StringBuilder();
            //用参数条数最多的项做为优先生成个数
            for(int i = 0 ; i < mainParamTextBox.Lines.Length ; i++)
            {
                string templetText = codeEditorTemplate.ContentText;//模板文本
                foreach(KeyValuePair<UIRichTextBox,int> kvp in dicSort)
                {
                    var paramTextBox = kvp.Key;
                    string param = string.Empty;//参数默认值，后续可以扩展下？
                    if(paramTextBox.Lines.Length > i && !string.IsNullOrWhiteSpace(paramTextBox.Lines[i]))
                    {
                        param = paramTextBox.Lines[i];
                    }
                    templetText = templetText.Replace(paramTextBox.TagString,param);//替换参数值
                }
                sb.Append(templetText + "\n");
            }

            this.codeEditorResult.ContentText = sb.ToString().TrimEnd('\n');
            this.codeEditorResult.PanelTitle = $"结果（共{mainParamTextBox.Lines.Length}条）";
        }


        /// <summary>
        /// 参数文本框值改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParamRichTextBox_TextChanged(object sender,EventArgs e)
        {
            UIRichTextBox richTextBox = (UIRichTextBox)sender;
            UITitlePanel titlePanel = (UITitlePanel)richTextBox.Parent;
            titlePanel.Text = $"参数：{richTextBox.TagString}（共{richTextBox.Lines.Length}条）"; //设置panl容器的标题
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender,EventArgs e)
        {
            if(this.ShowAskDialog($"{GlobalData.AppName_zh}-重要提示", $"是否确定重置窗口？重置前请保存好数据！",UIStyle.Orange,false, UIMessageDialogButtons.Cancel))
            {
                this.codeEditorTemplate.ClearContent();
                this.codeEditorResult.ClearContent();
                PnlParam.Controls.Clear();
            }
        }

        #region 参数栏滚动条
        private void PnlParam_ControlAdded(object sender,ControlEventArgs e)
        {
            PnlParam.AutoScroll = true;
            PnlParam.VerticalScroll.Enabled = true;
            PnlParam.VerticalScroll.Visible = true;

        }

        private void PnlParam_Scroll(object sender,ScrollEventArgs e)
        {
            PnlParam.VerticalScroll.Value = e.NewValue;
        }

        #endregion



    }
}
